package com.cennavi.minemap.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class InfoUtil {
	public static String getHost() throws Exception {
		Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements()) {
				ip = (InetAddress) addresses.nextElement();
				if (ip != null && ip instanceof Inet4Address) {
					if (!ip.getHostAddress().equals("127.0.0.1")) {
						return ip.getHostAddress();
					}
				}
			}
		}
		return null;
	}
	
	public static String getMac() throws Exception {
		Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements()) {
				ip = (InetAddress) addresses.nextElement();
				if (ip != null && ip instanceof Inet4Address) {
					if (!ip.getHostAddress().equals("127.0.0.1")) {
						byte[] mac = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
						StringBuffer sb = new StringBuffer("");
						for(int i=0; i<mac.length; i++) {
							if(i!=0) {
								String os = System.getProperty("os.name");  
								if(os.toLowerCase().startsWith("win")){  
									sb.append("-"); 
								} 
								else{
									sb.append(":");
								}
							}
							//字节转换为整数
							int temp = mac[i]&0xff;
							String str = Integer.toHexString(temp);
							if(str.length()==1) {
								sb.append("0"+str);
							}else {
								sb.append(str);
							}
						}
						return sb.toString().toUpperCase();
					}
				}
			}
		}
		return null;
	}
}
